//
//  TypeViewController.m
//  预购清单
//
//  Created by  on 2022/10/17.
//

#import "TypeViewController.h"
#import "BuyTypeCell.h"

@interface TypeViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) IBOutlet UITextField *input;
@property (strong, nonatomic) IBOutlet UIView *line;
@property (strong, nonatomic) IBOutlet UIButton *doneBtn;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *inputTop;
@property (strong, nonatomic) NSMutableArray <PrepayType *> *array;

@end

@implementation TypeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self initUI];
    [self addNotify];
}

- (void)initUI{
    self.title = LS(@"类别");
    [self.doneBtn setTitle:self.isedit ? LS(@"完成") : LS(@"添加") forState:UIControlStateNormal];
    self.inputTop.constant = self.isedit ? 24 : -40;
    [self.collectionView registerNib:[BuyTypeCell nib] forCellWithReuseIdentifier:[BuyTypeCell ID]];
    self.collectionView.c_top.equalTo(self.line.c_bottom).coffset(0);
    self.collectionView.c_left.equalTo(self.view.c_left).coffset(0);
    self.collectionView.c_right.equalTo(self.view.c_right).coffset(0);
    self.collectionView.c_bottom.equalTo(self.view.c_bottom).coffset(0);
    [self.view bringSubviewToFront:self.doneBtn];
}
- (void)loadData{
    [PrePayTypeTool find:APP.user.account complete:^(NSMutableArray<PrepayType *> * _Nonnull result) {
        self.array = result;
        if (self.isedit) {
            PrepayType *model = [PrepayType new];
            model.name = @"添加";
            model.img = UIImageJPEGRepresentation([UIImage imageNamed:@"添加_圆圈"], 1);
            [self.array addObject:model];
        }
        [self.collectionView reloadData];
    }];
}
- (void)takePhoto{
    WS(self)
    SheetViewController *sheetvc = [SheetViewController new];
    sheetvc.withCancel = NO;
    sheetvc.array = @[@"拍摄",@"相册"];
    sheetvc.block = ^(int index, NSString * _Nonnull text) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [CCHud startHud];
        });
        UIImagePickerController *vc = [UIImagePickerController new];
        vc.delegate = weakself;
        vc.allowsEditing = YES;
        vc.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [[weakself currentVC] presentViewController:vc animated:YES completion:^{
            [CCHud stopHud];
        }];
    };
    [[weakself currentVC] presentViewController:sheetvc animated:NO completion:nil];
}

- (IBAction)actionForBtn:(UIButton *)sender {
    if (self.isedit == NO) {
        TypeViewController *vc = [TypeViewController new];
        vc.isedit = YES;
        [self push:vc :YES];
    }else{
        if (self.input.text.length <= 0) {
            return [CCHud msg:LS(@"请输入名称")];
        }
        PrepayType *model = self.array[self.array.count - 2];
        model.name = self.input.text;
        model.account = APP.user.account;
        NSMutableArray * array = [NSMutableArray arrayWithArray:self.array];
        [array removeLastObject];
        [PrepayType bg_saveOrUpdateArrayAsync:array complete:^(BOOL isSuccess) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self loadData];
                [NotifyTool post:notifyPrepayTypeUpdate :nil];
                [CCHud startHud:LS(@"保存成功") stopTime:1 handle:^{
                    [self backBtnAction];
                }];
            });
        }];
    }
}
- (void)addNotify{
    [super addNotify];
    [NotifyTool add:self :@selector(loadData) :notifyPrepayTypeUpdate :nil];
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    PrepayType *model = [PrepayType new];
    model.name = @"未命名";
    model.img = UIImageJPEGRepresentation(img, 0.5);
    [self.array insertObject:model atIndex:self.array.count - 1];
    [self.collectionView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  self.array.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BuyTypeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[BuyTypeCell ID] forIndexPath:indexPath];
    cell.model = self.array[indexPath.row];
    cell.selectBtn.hidden = self.isedit ? YES : indexPath.row >= self.array.count;
    [cell.selectBtn setImage:[UIImage imageNamed:@"取消_圆圈"] forState:UIControlStateNormal];
    return  cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isedit && indexPath.row == self.array.count-1) {
        [self takePhoto];
    }else{
        [self alert:LS(@"注意") :LS(@"确定要删除吗？") :nil :^{
            [PrePayTypeTool delete:self.array[indexPath.row] complete:^{
                [self.array removeObjectAtIndex:indexPath.row];
                [collectionView reloadData];
                [NotifyTool post:notifyPrepayTypeUpdate :nil];
            }];
        }];
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return  CGSizeMake(57,76);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(20, 16, 20, 16);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 16;
}

@end
